import {
  View,
  Text,
  StyleSheet,
  Image,
  ScrollView,
  Pressable,
  Animated,
} from 'react-native'
import { common, flexCol, compose } from '../assets/style/common'
import { useMemo, useState, useRef } from 'react'
import useGetStatusBar from '../utils/useGetStatusBar'
import { LinearGradient } from 'expo-linear-gradient'
import { CardDataInterface } from '../assets/data/data'
import Price from '../component/price'
import OwlRadioBox from '../component/common/owlRadioBox'
import GoodsCard from '../component/gouwuche/goodsCard'
import ListWrap from '../component/home/listWrap'
import userCartContext from '../context/userCartContext'
export default function GouWuChe() {
  const scrollRef = useRef<ScrollView>(null)
  const scrollY = useRef(new Animated.Value(0)).current
  const borderRadius = scrollY.interpolate({
    inputRange: [0, 12],
    outputRange: [12, 0],
    extrapolate: 'clamp',
  })
  const showScrollTop = scrollY.interpolate({
    inputRange: [300, 350],
    outputRange: [0, 1],
    extrapolate: 'clamp',
  })
  const translateScrollTop = scrollY.interpolate({
    inputRange: [300, 350],
    outputRange: [100, 0],
    extrapolate: 'clamp',
  })
  const showManageAnimate = useRef(new Animated.Value(0)).current
  const footerEdit = showManageAnimate.interpolate({
    inputRange: [0, 1],
    outputRange: [58, 0],
  })
  const footerBuy = showManageAnimate.interpolate({
    inputRange: [0, 1],
    outputRange: [0, 58],
  })
  const [barHeight] = useGetStatusBar()
  const [isManage, setIsManage] = useState(false)
  const { data, dispatch } = userCartContext()
  const cartPrice = useMemo(() => {
    return (
      data.reduce((prev: number, item: CardDataInterface) => {
        return prev + (item.choosed ? item.price * item.count : 0)
      }, 0) + ''
    )
  }, [data])
  const isChoosedAll = useMemo(() => {
    return !(data.findIndex(item => !item.choosed) >= 0)
  }, [data])
  // 当点击全选时
  function onChoosedAll() {
    dispatch({ type: 'switchAllChoosed', setChoosed: !isChoosedAll })
  }
  // 删除购物车中的商品
  function delGoods(id: number) {
    dispatch({ type: 'delGoods', id: id })
  }
  function onEditSwitch() {
    const newVal = !isManage
    setIsManage(newVal)
    Animated.timing(showManageAnimate, {
      toValue: newVal ? 1 : 0,
      duration: 300,
      useNativeDriver: false,
    }).start()
  }
  function goBack() {
    scrollRef.current?.scrollTo({ y: 0, animated: false })
  }

  return (
    <View style={flexCol(styles.container)}>
      <LinearGradient
        start={{ x: 0.2, y: 0.3 }}
        end={{ x: 0.8, y: 0.7 }}
        colors={['#73d7f7', '#57aef0']}
        style={StyleSheet.compose(styles.header, {
          paddingTop: barHeight,
          height: barHeight + 48 + 12,
          paddingBottom: 12,
        })}
      >
        <Text style={styles.hTit}>购物车</Text>
        <Text style={styles.hCount}>({data.length})</Text>
        <Text style={styles.hAddress} numberOfLines={1}>
          广东省广州市天河区车陂大马路二号菜鸟驿站二号店
        </Text>
        <Text style={styles.hSet} onPress={onEditSwitch}>
          {isManage ? '取消管理' : '管理'}
        </Text>
      </LinearGradient>

      <Animated.View
        style={[
          styles.scrollWrap,
          {
            borderRadius: borderRadius,
          },
        ]}
      >
        <LinearGradient
          start={{ x: 0.5, y: 0 }}
          colors={['#ffffff', '#eeeeee']}
          end={{ x: 0.5, y: 1 }}
          style={styles.scrollBgm}
        >
          <ScrollView
            ref={scrollRef}
            onScroll={Animated.event(
              [{ nativeEvent: { contentOffset: { y: scrollY } } }],
              { useNativeDriver: false },
            )}
            scrollEventThrottle={16}
            style={styles.scroll}
          >
            {data.map((item, index) => (
              <GoodsCard
                onErase={delGoods}
                isEdit={isManage}
                style={{ marginTop: index === 0 ? 12 : 0 }}
                onTouchRadio={id =>
                  dispatch({
                    type: 'switchChoosed',
                    id,
                  })
                }
                key={item.id}
                {...item}
              />
            ))}
            <View style={flexCol(styles.likeTitle)}>
              <Image
                style={compose(styles.likeIcon, styles.reverse)}
                source={require('../assets/icon/keaide.png')}
              />
              <Text style={styles.likeTxt}>猜你喜欢</Text>
              <Image
                style={styles.likeIcon}
                source={require('../assets/icon/keaide.png')}
              />
            </View>
            <ListWrap onlyGoodsList={true} />
          </ScrollView>
        </LinearGradient>
      </Animated.View>
      <View style={styles.footer}>
        <Animated.View
          style={[
            styles.footerWrap,
            common.flexCol,
            {
              transform: [{ translateY: footerBuy }],
            },
          ]}
        >
          <OwlRadioBox
            style={styles.radioAll}
            label="全选"
            choosed={isChoosedAll}
            onPress={onChoosedAll}
          />
          <Text style={styles.heji}>合计：</Text>
          <Price
            price={cartPrice}
            style={styles.totPrice}
            fontSize={20}
            fontWeight
          />
          <LinearGradient
            colors={['#f392a6', '#fee68d']}
            start={{ x: 0.8, y: 1 }}
            end={{ x: 0.1, y: 0.1 }}
            style={styles.nptIBtn}
          >
            <Text style={StyleSheet.compose(styles.nptITxt, common.flexCol)}>
              结算
            </Text>
          </LinearGradient>
        </Animated.View>
        <Animated.View
          style={[
            styles.footerWrap,
            common.flexCol,
            {
              transform: [{ translateY: footerEdit }],
            },
          ]}
        >
          <OwlRadioBox
            style={styles.radioAll}
            label="全选"
            choosed={isChoosedAll}
            onPress={onChoosedAll}
          />
          <Pressable style={styles.nptIBtn} onPress={onEditSwitch}>
            <Text
              style={[styles.nptITxt, common.flexCol, styles.nptOutlineTxt]}
            >
              取消
            </Text>
          </Pressable>
          <View style={[styles.nptIBtn, styles.nptImprnt]}>
            <Text style={[styles.nptITxt, common.flexCol]}>删除</Text>
          </View>
        </Animated.View>
      </View>
      <Animated.View
        style={[
          styles.backTopBox,
          {
            opacity: showScrollTop,
            transform: [{ translateX: translateScrollTop }],
          },
        ]}
      >
        <Pressable style={styles.backTopWrap} onPress={goBack}>
          <Text style={styles.backTopIcon}>&#xe7ed;</Text>
          <Text style={styles.backTopTxt}>回到顶部</Text>
        </Pressable>
      </Animated.View>
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    height: '100%',
    flexDirection: 'column',
  },
  scroll: {
    flex: 1,
    width: '100%',
  },
  scrollWrap: {
    width: '100%',
    flex: 1,
    marginTop: -12,
    position: 'relative',
    zIndex: 13,
    overflow: 'hidden',
  },
  scrollBgm: {
    height: '100%',
    width: '100%',
  },
  footer: {
    height: 58,
    width: '100%',
    backgroundColor: '#fff',
    paddingLeft: 10,
    paddingRight: 10,
  },
  footerWrap: {
    height: '100%',
    width: '100%',
    position: 'absolute',
    top: 0,
    left: 0,
  },
  choose: {
    color: '#666',
    marginLeft: 4,
    fontSize: 14,
  },
  radioAll: {
    marginRight: 'auto',
  },
  heji: {
    color: '#333',
    fontSize: 14,
  },
  totPrice: {
    marginBottom: 4,
  },
  header: {
    width: '100%',
    display: 'flex',
    alignItems: 'center',
    flexDirection: 'row',
    height: '100%',
    paddingHorizontal: 12,
    zIndex: 12,
  },
  hTit: {
    color: '#fff',
    fontSize: 20,
    fontWeight: 'bold',
  },
  hCount: {
    color: '#fff',
    fontSize: 12,
  },
  hAddress: {
    color: '#fff',
    fontSize: 12,
    flex: 1,
    paddingHorizontal: 12,
  },
  hSet: {
    color: '#fff',
    fontSize: 14,
    marginLeft: 'auto',
  },
  nptIBtn: {
    height: 34,
    width: 84,
    marginLeft: 12,
    borderRadius: 17,
    verticalAlign: 'center',
  },
  nptImprnt: {
    backgroundColor: '#ff2222',
  },
  nptUnimprnt: {
    backgroundColor: '#fff',
    borderColor: '#ff2222',
    borderWidth: 1,
  },
  nptITxt: {
    fontWeight: 'bold',
    fontSize: 14,
    lineHeight: 34,
    height: '100%',
    color: '#fff',
    textAlign: 'center',
    textAlignVertical: 'center',
  },
  nptOutlineTxt: {
    color: '#f392a6',
    borderColor: '#f392a6',
    borderWidth: 1,
    borderRadius: 17,
  },
  likeTitle: {
    justifyContent: 'center',
    marginTop: 12,
    marginBottom: 12,
  },
  likeIcon: {
    width: 16,
    height: 16,
  },
  likeTxt: {
    fontSize: 16,
    paddingHorizontal: 8,
  },
  reverse: {
    transform: [{ scaleX: -1 }],
  },
  backTopBox: {
    position: 'absolute',
    zIndex: 100,
    right: 12,
    bottom: 108,
    width: 58,
    height: 58,
  },
  backTopWrap: {
    backgroundColor: '#ffffff',
    borderRadius: 29,
    width: 58,
    height: 58,
    display: 'flex',
    flexDirection: 'column',
    alignItems: 'center',
    justifyContent: 'center',
    borderColor: '#eee',
    borderWidth: 1,
  },
  backTopIcon: {
    fontSize: 18,
    fontFamily: 'iconfont',
    color: '#333',
  },
  backTopTxt: {
    fontSize: 10,
    marginTop: 4,
    textAlign: 'center',
    color: '#333',
  },
})
